<template>
  <div>
    <MyHeader title="提交订单" :arrow="true" text="返回"></MyHeader>
    <div style="padding-bottom: 50px">
      <van-cell-group inset title="配送地址">
        <van-cell v-if="hasAddress" is-link to="/address?isOrder=true">
          <div slot="title" class="title">
            <van-row>
              <van-col :span="8">姓名：{{ address.name }}</van-col>
              <van-col :span="16">联系方式：{{address.phone}}</van-col>
            </van-row>
          </div>
          <div slot="label">
            <span>{{ address.address }}</span>
          </div>
        </van-cell>
        <van-cell v-else title="暂无地址" label="点击添加地址" is-link to="/address/edit"/>
      </van-cell-group>
      <van-cell-group title="商户信息">
        <van-cell :title="shopInfo.name" :icon="baseImgPath+shopInfo.image_path" is-link :to="`/shop?id=${shopInfo.id}`"></van-cell>
      </van-cell-group>
      <van-cell-group title="订单信息">
        <van-cell title="选购商品">
          <template slot="label">
            <template v-for="item in cartList">
              <van-card :key="item.item_id" v-if="item.selectCount>0" :num="item.selectCount" :title="item.name" :thumb="baseImgPath+item.image_path" class="cart-list">
                <div slot="desc">
                  <span>规格：</span>
                  <van-tag plain type="success">{{item.specfoods[item.specActive].name}}</van-tag>
                </div>
                <div slot="price">
                  <span>价格</span>
                  <span>￥<b>{{item.specfoods[item.specActive].price}}</b></span>
                </div>
              </van-card>
            </template>
          </template>
        </van-cell>
      </van-cell-group>
    </div>
    <van-submit-bar :price="orderPrice" button-text="付钱" @submit="submitOrder" />
    <van-action-sheet title="收银台" v-model="showPay" style="height: 380px">
      <van-password-input :value="password" info="密码为 6 位数字" class="password-input" />
      <van-number-keyboard @hide="password=''" @blur="showPay=false" v-model="password" :show="showPay" />
    </van-action-sheet>
  </div>
</template>

<script>
import MyHeader from '@/components/MyHeader'
import { mapState } from 'vuex'
import { uuid } from 'vue-uuid'
export default {
  name: 'OrderDetail',
  components: { MyHeader },
  data () {
    return {
      address: {
        name: '',
        phone: '',
        address: '',
        id: ''
      },
      hasAddress: false,
      baseImgPath: process.env.VUE_APP_BASE_API + '/file/getImgStream?fileName=',
      password: '',
      showPay: false,
      orderList: [],
      addressList: []
    }
  },
  computed: {
    ...mapState(['cartInfo', 'shopInfo']),
    cartList () {
      if (this.cartInfo.userId === this.$cookies.get('user_id') && this.cartInfo.shopId === this.shopInfo.id) {
        return this.cartInfo.cartList
      }
      return []
    },
    orderPrice () {
      let price = 0
      for (const cart of this.cartList) {
        if (cart.selectCount > 0) {
          price += cart.selectCount * (cart.specfoods[cart.specActive].price + cart.specfoods[cart.specActive].packing_fee)
        }
      }
      return (price + 5) * 100
    }
  },
  watch: {
    password (value) {
      if (value.length === 6) {
        if (value === '910123') {
          let cartPrice = 0
          const items = this.cartList.filter(item => item.selectCount > 0)
            .map(item => {
              const food = {
                id: item.item_id,
                name: item.name,
                spec: item.specfoods[item.specActive].name,
                price: item.specfoods[item.specActive].price,
                packing_fee: item.specfoods[item.specActive].packing_fee,
                image_path: item.image_path,
                count: item.selectCount
              }
              cartPrice += (food.price + food.packing_fee) * food.count
              return food
            })

          const order = {
            id: uuid.v4(),
            userId: this.$cookies.get('user_id'),
            shopId: this.shopInfo.id,
            orderTime: new Date().toLocaleString(),
            cartPrice: cartPrice,
            orderPrice:this.orderPrice,
            state: 1,
            delivery_fee: 5,
            foodList: items,
            address: this.address
          }
          this.orderList.push(order)
          localStorage.setItem('orderList', JSON.stringify(this.orderList))
          this.$dialog.alert({ message: '付款成功' }).then(() => {
            this.$store.commit('setCartInfo', [])
            sessionStorage.removeItem('cartInfo')
            this.$router.replace('/order')
          })
        } else {
          this.$dialog.alert({ message: '密码错误' })
        }
      }
    }
  },
  methods: {
    getAddress (index) {
      this.$axios.get(`v1/users/${this.$cookies.get('user_id')}/addresses`).then(({ data }) => {
        if (data.code === 20000) {
          if (data.data.length > 0) {
            if (!index) {
              index = 0
            }
            this.address = data.data.reverse()[index]
            this.hasAddress = true
          }
        }
      })
    },
    submitOrder () {
      this.showPay = true
    }
  },
  created () {
    this.$nextTick(() => {
      this.getAddress(this.$route.params.index)
      this.orderList = JSON.parse(localStorage.getItem('orderList') || '[]')
    })
  }
}
</script>

<style scoped lang="scss">
.cart-list{
  padding: 0 10px;
  .van-card__thumb{
    height: 44px;
    width: 44px;
  }
  .van-card__content{
    min-height: auto;
  }

}
</style>

<style>
/*.van-password-input__security{*/
/*border-left: 1px #333 solid;*/
/*}*/
/*.van-password-input__security li{*/
/*  border: 1px #333 solid;*/
/*  border-left: none;*/
/*}*/
</style>
